import { http } from '../utils/http'

/**
 * 字典数据接口
 */
export interface DictData {
    label: string
    value: string | number
    colorType?: string
    cssClass?: string
}

/**
 * 字典类型常量
 */
export const DICT_TYPE = {
    // 请假相关字典
    LEAVE_TYPE: 'leave_type',                    // 请假类型
    PERSONAL_TYPE: 'personal_type',              // 因私请假类型
    ACADEMIC_NATURE: 'academic_nature',          // 学术会议性质
    PERSONAL_VISIT_TYPE: 'personal_visit_type',  // 探亲类别
    MARITAL_STATUS: 'marital_status',            // 婚姻状况
    PARITY: 'parity',                           // 生育次数
    IS_PRESENTATION: 'is_presentation',          // 是否受邀做学术报告
    REPORT_TYPE: 'report_type',                  // 报告类型
    LEAVE_STATUS: 'leave_status',                // 请假流转状态
    CANCELSTATUE: 'cancelStatue',                // 销假状态
    IS_MULTIPLE_BIRTH: 'is_multiple_birth',     // 是否多胞胎
    IS_DYSTOCIA: 'is_dystocia',                 // 是否难产
} as const

/**
 * 字典 API
 */
export const DictApi = {
    /**
     * 获取所有字典数据
     * @returns 所有字典数据
     */
    getSimpleDictDataList: async (): Promise<DictData[]> => {
        try {
            const response = await http.get('/app/dict-data/simple-list')
            // 确保返回的是数组
            if (Array.isArray(response)) {
                return response
            } else if (response && Array.isArray(response.data)) {
                return response.data
            } else {
                return []
            }
        } catch (error) {
            return []
        }
    },

    /**
     * 获取字典数据列表
     * @param dictType 字典类型
     * @returns 字典数据列表
     */
    getDictDataList: async (dictType: string): Promise<DictData[]> => {
        try {
            const response = await http.get(`/app/dict-data/type?type=${dictType}`)
            // 确保返回的是数组
            if (Array.isArray(response)) {
                return response
            } else if (response && Array.isArray(response.data)) {
                return response.data
            } else {
                return []
            }
        } catch (error) {
            return []
        }
    },

    /**
     * 获取多个字典类型的数据
     * @param dictTypes 字典类型数组
     * @returns 字典数据映射
     */
    getMultipleDictData: async (dictTypes: string[]): Promise<Record<string, DictData[]>> => {
        const promises = dictTypes.map(type => 
            DictApi.getDictDataList(type).then(data => ({ [type]: data }))
        )
        const results = await Promise.all(promises)
        return results.reduce((acc, curr) => ({ ...acc, ...curr }), {})
    },

    /**
     * 获取字典标签
     * @param dictType 字典类型
     * @param value 字典值
     * @returns 字典标签
     */
    getDictLabel: async (dictType: string, value: string | number): Promise<string> => {
        const dictList = await DictApi.getDictDataList(dictType)
        const dictItem = dictList.find(item => item.value === value)
        return dictItem?.label || String(value)
    }
}

/**
 * 字典数据缓存
 */
class DictCache {
    private cache: Map<string, { data: DictData[], timestamp: number }> = new Map()
    private readonly CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

    /**
     * 获取缓存的字典数据
     */
    get(dictType: string): DictData[] | null {
        const cached = this.cache.get(dictType)
        if (!cached) return null

        const now = Date.now()
        if (now - cached.timestamp > this.CACHE_DURATION) {
            this.cache.delete(dictType)
            return null
        }

        return cached.data
    }

    /**
     * 设置字典数据缓存
     */
    set(dictType: string, data: DictData[]): void {
        this.cache.set(dictType, {
            data,
            timestamp: Date.now()
        })
    }

    /**
     * 清除缓存
     */
    clear(): void {
        this.cache.clear()
    }

    /**
     * 清除指定类型的缓存
     */
    delete(dictType: string): void {
        this.cache.delete(dictType)
    }
}

export const dictCache = new DictCache()

/**
 * 带缓存的字典API
 */
export const CachedDictApi = {
    /**
     * 获取字典数据列表（带缓存）
     */
    getDictDataList: async (dictType: string): Promise<DictData[]> => {
        // 先尝试从缓存获取
        const cached = dictCache.get(dictType)
        if (cached) {
            return cached
        }

        // 缓存未命中，从API获取
        try {
            const data = await DictApi.getDictDataList(dictType)
            dictCache.set(dictType, data)
            return data
        } catch (error) {
            console.error(`获取字典数据失败: ${dictType}`, error)
            return []
        }
    },

    /**
     * 获取多个字典类型的数据（带缓存）
     */
    getMultipleDictData: async (dictTypes: string[]): Promise<Record<string, DictData[]>> => {
        const result: Record<string, DictData[]> = {}
        
        for (const dictType of dictTypes) {
            result[dictType] = await CachedDictApi.getDictDataList(dictType)
        }
        
        return result
    }
}